package com.jiuqi.abc.model.dao;

import com.jiuqi.abc.model.bean.Driver;
import com.jiuqi.bi.util.OrderGenerator;
import com.jiuqi.bi.util.type.GUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;

/**
 * 动因DAO
 * <p>
 * 概念区分
 * 维度    name（英文）  title（中文）
 * 维度项  code（英文）  name（中文）
 */

@Repository
public class ABCDriverDao {

    //动因表
    private static final String T_TABLE = "ABC_M_DRIVER";

    //表ID(主键)
    private static final String F_AMDR_ID = "AMDR_ID";

    //动因编码
    private static final String F_AMDR_CODE = "AMDR_CODE";

    //动因名称
    private static final String F_AMDR_NAME = "AMDR_NAME";

    //所属动因分组ID 与 动因分组表 表ID(主键)关联
    private static final String F_AMDG_ID = "AMDG_ID";

    //所属模型ID 与 分摊模型基本信息表 中 模型ID（主键） 关联
    private static final String F_AMM_ID = "AMM_ID";

    //关联成本维度编码 dimName  多个时由",“分割
    private static final String F_AMMD_DIM_CODE = "AMMD_DIM_CODE";

    //动因顺序
    private static final String F_AMDR_ORDER = "AMDR_ORDER";

    @Autowired
    JdbcTemplate jdbcTemplate;

    //【增】 动因
    public void batchAddDrivers(List<Driver> drivers) {
        String addSql = String.format("INSERT INTO %s VALUES(?,?,?,?,?,?,?)", T_TABLE);
        List<Object[]> argList = new ArrayList<>();
        for (Driver driver : drivers) {
            StringBuilder dimNameAssemble = new StringBuilder();
            List<String> dimNameList = driver.getDimNameList();
            for (int i = 0; i < dimNameList.size(); i++) {
                if (i == dimNameList.size() - 1)
                    dimNameAssemble.append(dimNameList.get(i));
                else {
                    dimNameAssemble.append(dimNameList.get(i));
                    dimNameAssemble.append(",");
                }
            }
            //重置 前端未保存时 用于 判断颜色序列的 动因ID
            if (Objects.isNull(driver.getId()) || ("").equals(driver.getId()))
                driver.setId(GUID.newGUID());

            Object[] args = {driver.getId(), driver.getCode(), driver.getName(), driver.getBelongDriverGroupId(),
                    driver.getBelongModelId(), dimNameAssemble.toString(), OrderGenerator.newOrderID()};
            argList.add(args);
        }

        jdbcTemplate.batchUpdate(addSql, argList);
    }

    //【查】 根据 动因分组ID集合 批量获取 动因列表
    public List<Driver> getDriverListByDriverGroupIds(List<String> driverGroupIdList) {
        //查询SQL语句
        String selectSql = String.format("SELECT %s,%s,%s,%s,%s,%s,%s FROM %s WHERE %s in ( :ids ) ORDER BY %s",
                F_AMDR_ID, F_AMDR_CODE, F_AMDR_NAME, F_AMDG_ID, F_AMM_ID, F_AMMD_DIM_CODE, F_AMDR_ORDER,
                T_TABLE,
                F_AMDG_ID,
                F_AMDR_ORDER);

        // 为空时添加""防止SQL语法错误
        if (driverGroupIdList.isEmpty())
            driverGroupIdList.add("");

        //配置查询参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("ids", driverGroupIdList);

        //执行查询
        NamedParameterJdbcTemplate jdbc = new NamedParameterJdbcTemplate(jdbcTemplate);
        List<Map<String, Object>> resultList = jdbc.queryForList(selectSql, paramMap);

        //处理结果
        List<Driver> driverList = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : resultList) {
            Driver driver = new Driver();
            driver.setId((String) stringObjectMap.get(F_AMDR_ID));
            driver.setCode((String) stringObjectMap.get(F_AMDR_CODE));
            driver.setName((String) stringObjectMap.get(F_AMDR_NAME));
            driver.setBelongDriverGroupId((String) stringObjectMap.get(F_AMDG_ID));
            driver.setBelongModelId((String) stringObjectMap.get(F_AMM_ID));

            //处理由  “,”  拼接成的字符串
            String rsString = (String) stringObjectMap.get(F_AMMD_DIM_CODE);
            String[] split = rsString.split(",");
            List<String> processDimNameList = Arrays.asList(split);
            driver.setDimNameList(processDimNameList);

            BigDecimal bigDecimalData = (BigDecimal) stringObjectMap.get(F_AMDR_ORDER);
            long longValue = bigDecimalData.longValue();
            driver.setOrder(longValue);

            driverList.add(driver);
        }

        //返回结果
        return driverList;
    }

    //【查】 根据 模型ID 获取 动因列表
    public List<Driver> getDriverListByModelId(String modelId) {
        String selectSql = String.format("SELECT %s,%s,%s,%s,%s,%s,%s FROM %s WHERE %s = ?",
                F_AMDR_ID, F_AMDR_CODE, F_AMDR_NAME, F_AMDG_ID, F_AMM_ID, F_AMMD_DIM_CODE, F_AMDR_ORDER,
                T_TABLE,
                F_AMM_ID);
        Object[] args = {modelId};
        return jdbcTemplate.query(selectSql, rs -> {
            List<Driver> driverList = new ArrayList<>();
            while (rs.next()) {
                Driver driver = new Driver();
                try {
                    driver.setId(rs.getString(F_AMDR_ID));
                    driver.setCode(rs.getString(F_AMDR_CODE));
                    driver.setName(rs.getString(F_AMDR_NAME));
                    driver.setBelongDriverGroupId(rs.getString(F_AMDG_ID));
                    driver.setBelongModelId(rs.getString(F_AMM_ID));

                    //处理由  “,”  拼接成的字符串
                    String rsString = rs.getString(F_AMMD_DIM_CODE);
                    String[] split = rsString.split(",");
                    List<String> processDimNameList = Arrays.asList(split);
                    driver.setDimNameList(processDimNameList);

                    driver.setOrder(rs.getLong(F_AMDR_ORDER));

                    driverList.add(driver);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            return driverList;
        }, args);
    }

    //【删】 根据  动因分组ID集合  批量删除 多个动因
    public void batchDeleteDriversByDriverGroupIdList(List<String> driverGroupIdList) {
        String deleteSql = String.format("DELETE FROM %s WHERE %s = ?", T_TABLE, F_AMDG_ID);
        List<Object[]> argsList = new ArrayList<>();
        for (String driverGroupId : driverGroupIdList) {
            argsList.add(new Object[]{driverGroupId});
        }
        jdbcTemplate.batchUpdate(deleteSql, argsList);
    }

}
